package com.chw.upload;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import com.chw.upload.IUploadFileService;
import com.chw.common.ServiceData;
import com.chw.utils.LogUtil;
import com.chw.utils.UUIDUtil;

@Controller
public class UploadController {

	private static LogUtil log = LogUtil.newInstance(UploadController.class);
	
	@Autowired
	private IUploadFileService uploadFileService;

	@RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ServiceData uploadFile(DefaultMultipartHttpServletRequest request,HttpServletResponse response) throws Exception {
		log.info("upload");
		// 返回统一的服务端数据
		ServiceData ret = new ServiceData();
		List<UploadFile> result = new ArrayList<UploadFile>();
		
		UploadFile record = null;
		Map<String,String[]> map = request.getParameterMap();
		String[] files =  map.get("file_name");
		if(files!=null)
		{
			for(int i=0;i<files.length;i++){
				record = new UploadFile();
				String upFileName = files[i];
				String fileType = map.get("content_type")[i];
				String tempFileUrl = map.get("path")[i];
				
				record.setUpFileName(upFileName);
				record.setFileType(fileType);
	
				if(StringUtils.isNoneBlank(tempFileUrl) && StringUtils.isNoneBlank(upFileName))
				{
					String url = "";
					String replacePath = null;
					if(fileType.contains("image")){
						replacePath = "/image/";
					}else if(fileType.contains("video")){
						replacePath = "/video/";
					}else{
						replacePath = "/file/";
					}
					
					//替换临时路径
					String fileUrl = tempFileUrl.replace("/temp/", replacePath);
					
					//新文件名
					StringBuffer fileName = new StringBuffer(UUIDUtil.getUUID()).append(upFileName.substring(upFileName.lastIndexOf(".")));
					log.info(fileName);
					
					//临时文件名位置
					int lastStrIndex = fileUrl.lastIndexOf("/");
					
					//临时文件名
					String tempFileName = fileUrl.substring(lastStrIndex+1);
					
					log.info(tempFileName);
					
					//重命名文件并移动文件位置
					File file = new File(tempFileUrl);
	
					if(file.exists())
					{
						url = fileUrl.replace(tempFileName,fileName);
						FileUtils.copyFile(file, new File(url), true);
					}
					record.setUrl(url);
					log.info(url);
				}
				
				record.setFileSize(map.get("size")[i]);
				log.info(map.get("size")[i]);
				uploadFileService.save(record);
				log.info("save");
				result.add(record);
			}
			ret.setCode(request, ServiceData.RetCode.Success);
		}else{
			ret.setCode(request, ServiceData.RetCode.ServerError);
		}
		ret.setBo(result);
		log.info("success");
		return ret;
	}
	
	@RequestMapping(value = "/uploadauth")
	public void uploadAuth(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String userId = null;
		AttributePrincipal principal = (AttributePrincipal)request.getUserPrincipal();
		if(principal!=null){
			Map<String,Object> attributes = principal.getAttributes();
			if(attributes!=null)
			{
				userId = (String) attributes.get("id");
			}
		}
		
		if(StringUtils.isNotBlank(userId)){
			response.setStatus(200);
		}else{
			response.setStatus(401);
		}
	}
}
